<template>
    <view class="common-list-page">
        <!-- 菜单栏 -->
        <u-sticky bgColor="#fff" zIndex="1">
            <view class="menuBar" v-if="categories.length > 1">
                <u-tabs :list="categories" keyName="name" :current="cateTabIndex" @click="onTabClick"
                    :activeStyle="{ color: '#4a4a4a', 'font-size': '17px', 'font-weight': 'bold'}"
                    :inactiveStyle="{ color: '#8994a9', 'font-size': '17px'}"
                ></u-tabs>
            </view>
            <!-- 工具栏 -->
            <view class="toolBar" v-if="toolBar">
                <view class="searchTool" v-if="toolBar.searchBar">
                    <u-search :placeholder="toolBar.searchBar.placeholder" 
                    :showAction="false" shape="square"
					@search="onSearchBarSearch"
                    v-model="toolBar.searchBar.value"></u-search>
                </view>
				<view class="filer-dropdown" v-if="toolBar.dropDownFilters && toolBar.dropDownFilters.length">
					<view class="dropdownItem" v-for="(item, index) in toolBar.dropDownFilters" :key="index" @click="dropDownItemClick(item)"
						:class="{active: item.showing}">
						<view class="name">{{item.name}}</view>
						<view class="trangle"><u-icon name="arrow-down-fill" size="10"></u-icon></view>
					</view>
					<view class="dropDownBroad" v-for="(item, index) in toolBar.dropDownFilters" :key="index" v-show="dropDownFilterShowing">
						<view class="categories" v-if="item.type == 'category'" v-show="item.showing" :style="item.categoryStyle">
							<view class="item" :class="{active: o.active}" :style="item.itemStyle" v-for="(o, i) in item.options" :key="i">
								{{o.name}}
							</view>
						</view>
						<view class="confrimbar">
							<view class="reset btn">清空</view>
							<view class="confirm btn">确定</view>
						</view>
					</view>

				</view>
            </view>
        </u-sticky>
        <!-- 正文列表 -->
        <view class="list-area" :class="listConfig.listClz" >
			<view class="disableBlock" v-if="dropDownFilterShowing" catchtouchmove="true" @click="dropDownItemClick()"></view>
        	<view class="listItem" v-for="(item, index) in list" :key="index" @click.prevent="showDetailCommon(item)">
        		<view class="item-icon" v-if="item.__icon">
        			<image :src="item.__icon" />
        		</view>
        		<view class="item-right">
        			<view class="lenMain">
						<view class="status" v-if="item.__status">
							<u-tag :text="item.__status" :type="item.__statusClz" plain plainFill></u-tag>
						</view>
						<view class="mainTitle">{{item.__title}}</view>
						<view class="titleTag" v-if="item.__titleTag">{{item.__titleTag}}</view>
					</view>
        			<view class="lens" v-if="item.__lens">
        				<view class="len" v-for="(len, lenId) in item.__lens" :key="lenId"  :style="len.lenStyle">
        					<view class="fieldItem" v-for="(f, fid) in len.items" :key="fid">
        						<view class="k">{{f.label}} ：</view>
        						<view class="v">{{f.value}}</view>
        					</view>
        				</view>
        			</view>
					<view class="buttons" v-if="item.__buttons && item.__buttons.length" :class="{mul: item.__buttons.length > 1}">
						<view class="button" v-for="(obj,j) in item.__buttons" :key="j">
							<u-button :style="obj.style" :type="obj.type" v-if="obj.show"
						 	 :plain="obj.plain" size="small" @click.native.stop.prevent="handleExtButtonClick(obj, item)">{{obj.label}}</u-button>
						</view>
					</view>
        		</view>
        	</view>


        </view>
		<u-loadmore :status="loadStatus" v-if="startSearch"/>
		<u-empty mode="search" v-if="isEmpty"></u-empty>
		<u-empty mode="permission" v-if="errorMsg" :text="errorMsg"></u-empty>
        <view class="gap" style="height: 120px;"></view>
        <view class="add" @click="handleExtButtonClick(listConfig.createNew, {})"
			 v-if="listConfig && listConfig.createNew && listConfig.createNew.type == 'image'">
            <image :src="listConfig.createNew.imageUrl" mode="aspectFill"></image>
        </view>
    </view>
</template>

<script>
	import { mapState } from "vuex";
	import sceneMixins from '@/utils/sceneMixins';
    export default {
		mixins: [sceneMixins],
		  computed: {
			...mapState(["userInfo"]),
		},
        data() {
           return {
           	cateTabIndex: 0,
			
			// 三大配置 分类配置， 工具栏配置， 列表项配置
           	categories: [],
           	toolBar: '',
           	listConfig: '',
           
           	list: [],
           	page: 0,
           	isLoading: false,
           	isLoaded: false,
           	isEmpty: false,
           	errorMsg: '',
           	startSearch: false,
           	isEnd: false,
           	isRefresh: false,
           	loadStatus: 'loadmore',

			dropDownFilterShowing: false
           }
        },
		props: {
			config: {type: Object}
		},
        options: { styleIsolation: 'shared' },
        mounted: function () {			
			this.categories = this.config.categories;
			this.toolBar = this.config.toolBar;
			this.listConfig = this.config.listConfig;

			if (this.listConfig.createNew) {
				if (this.listConfig.createNew.pemissionControl) {
					var pc = this.listConfig.createNew.pemissionControl;
					var judge = this.userInfo && pc[1].includes(this.userInfo[pc[0]]);
					if (!judge) {
						this.listConfig.createNew = '';
					}
				}
			}

            this.doWxLogin().then(res => {
                this.openId = res.openId;
                this.initPage();
            })
        },

        methods: {
			cmpReachBottom() {
				if (this.loadStatus != 'nomore') {
					this.page = ++this.page;
					this.getList();
				}
			},
            getPageConfigStr: function (name) {
                var pageParams = this.$Util.mergeJSON({ pageNo: 'pageNo', pageSize: 'pageSize' }, this.listConfig.pageParams || {});
                return pageParams[name];
            },
			dropDownItemClick: function (item) {
				var vm = this;
				if (!item) {
					item = vm.currentDropdownFilterItem;
				}
				// 先关掉当前的
				if (vm.currentDropdownFilterItem) {
					if (vm.currentDropdownFilterItem.showing) {
						vm.currentDropdownFilterItem.showing = false;
						if (vm.currentDropdownFilterItem == item) {
							vm.dropDownFilterShowing = false;
							return;
						}
					}
				}

				vm.currentDropdownFilterItem = item;
				item.showing = true;
				vm.dropDownFilterShowing = true;

			},
        	onTabClick: function (v) {
        		var vm = this;
        		vm.cateTabIndex = v.index;
				var currentTab = this.categories[v.index];
				vm.currentTab = currentTab;
        		if (currentTab.listConfig) {
        			this.mergedListConfig = this.$Util.mergeJSON(this.listConfig, currentTab.listConfig);
        		}
        		this.getList(true);
        	},
        	initPage: function () {
        		this.list = [];
        		this.onTabClick({index: 0});
        	},
			showDetailCommon: function (item) {
				var vm = this;
				var listConfig = vm.mergedListConfig || vm.listConfig;
				if (listConfig.detailPage) {
					vm.handleExtButtonClick(listConfig.detailPage, item);
				}
			},
        	getList(newLoad) {
        		var vm = this;
                vm.loadStatus = 'loading';
        		var listConfig = vm.mergedListConfig || vm.listConfig;
        		var listApi = listConfig.listApi;
        		listApi = listApi.replace('【openId】', vm.openId);
        		listApi = vm.getFmtStr(listApi, {});
        		if (vm.filterObject && vm.filterObject.stopAutoSearch && !vm.statusQueryString) {
        			return;
        		}
				if (vm.currentTab.queryString) {
        			listApi += '&' + vm.currentTab.queryString;
        		}
        		if (vm.statusQueryString) {
        			listApi += ('&' + vm.statusQueryString);
        		}
				if (vm.toolBar && vm.toolBar.searchBar) {
					listApi += (vm.toolBar.searchBar.queryString || '');
				}
                
                var defaultPageSize = listConfig.pageSize || 20;
                var defaultStartPageNo = listConfig.startPageNo || 0;
                if (newLoad) {
                    vm.page = defaultStartPageNo;
                    vm.list = [];
                    uni.showLoading({
                    	title: '正在获取信息'
                    })
                }
                
                var paginationParams = `&${vm.getPageConfigStr('pageSize')}=${defaultPageSize}&${vm.getPageConfigStr('pageNo')}=` + vm.page;
        		
        		vm.isEmpty = false;
                vm.errorMsg = '';
        		vm.startSearch = true;
                // debugger

				var getApiUrl = listApi + paginationParams;
				if (getApiUrl.indexOf('?') == -1) {
					getApiUrl = getApiUrl.replace('&', '?');
				}
        		vm.getAndLoad('获取列表', getApiUrl, function (res2) {
        			uni.hideLoading();
                    if (res2.code != 0) {
                        vm.errorMsg = res2.msg || '加载失败';
        				vm.startSearch = false;
                        return;
                    }
                    var listArray = uni.$u.test.array(res2.data) ? res2.data : (res2.data.list || res2.data.data);
                    if (listArray.length < defaultPageSize) {
                        vm.loadStatus = 'nomore';
                    } else {
                        vm.loadStatus = 'loadmore';
                    }
        			var mapper = listConfig.mapper;

        			if (mapper) {
        				vm.list = vm.list.concat(listArray.map(n => {
        					var newObj = { ...n };
        					newObj.__title = vm.getFmtStr(mapper.title, n);
							if (mapper.titleTag) {
								newObj.__titleTag = n[mapper.titleTag] || '';
							}
        					// 状态
        					// debugger
							if (mapper.statusId) {
								var __status = n[mapper.statusId];
								newObj.__status = __status;
								
								if (mapper.statusStyleMap) {
									newObj.__statusClz = mapper.statusStyleMap[__status];
								}
								if (!newObj.__statusClz) {
									if (__status.includes('不通过') || __status.includes('未通过')) {
										newObj.__statusClz = 'error';
									} else if (__status.includes('待') || __status.includes('未')) {
										newObj.__statusClz = 'warning';
									} else if (__status.includes('通过')) {
										newObj.__statusClz = 'success';
									} else {
										newObj.__statusClz = 'info';
									}
								}
							}
        					if (mapper.subTags) {
        						newObj.__subTags = vm.getFmtStr(mapper.subTags, n).split(',').filter(n => n);
        					}
        					if (mapper.lens) {
        						newObj.__lens = vm.$Util.cloneObject(mapper.lens).map(lenItem => {
        							lenItem.items.forEach(m => {
        								m.value = (m.prop ? n[m.prop] : (m.template ? vm.getFmtStr(m.template, n) : ''));
        							});
        							return lenItem;
        						});
        					}
        					if (mapper.extTags) {
        						newObj.__extTags = vm.getFmtStr(mapper.extTags, n).split(',').filter(n => n);
        					}
        					if (mapper.statusId) {
        						var __status = n[mapper.statusId];
        						newObj.__status = __status;
        						
        						if (mapper.statusStyleMap) {
        							newObj.__statusClz = mapper.statusStyleMap[__status];
        						}
        						if (!newObj.__statusClz) {
        							if (__status.includes('不通过') || __status.includes('未通过')) {
        								newObj.__statusClz = 'error';
        							} else if (__status.includes('待') || __status.includes('未')) {
        								newObj.__statusClz = 'warning';
        							} else if (__status.includes('通过')) {
        								newObj.__statusClz = 'success';
        							} else {
        								newObj.__statusClz = 'info';
        							}
        						}
        					}
        					if (mapper.itemClzMapper) {
        						var __status = n[mapper.statusId];
        						var keys = Object.keys(mapper.itemClzMapper);
        						var isKey = keys.find(m => __status.includes(m));
        						newObj.itemClz = isKey ? mapper.itemClzMapper[isKey] : '';
        					}
        					if (mapper.buttons) {
        						newObj.__buttons = JSON.parse(JSON.stringify(mapper.buttons));
        						newObj.__buttons.forEach(m => {
        							if (m.showWhen) {
        								m.show = m.showWhen[1].includes(n[m.showWhen[0]])
        							} else {
        								m.show != undefined && (m.show = true);
        							}
        						});
        						newObj.__buttons = newObj.__buttons.filter(n => n.show)
        					}
        					if (mapper.templates) {
        						var prop = mapper.templates.prop;
        						var templateHtml = '';
        						[].concat(n[prop]).forEach(task => {
        							templateHtml += vm.getFmtStr(mapper.templates.template, task)
        						});
        						newObj.__templateHtml = templateHtml;
        					}
        					if (mapper.footer) {
        						var footer = {...JSON.parse(JSON.stringify(mapper.footer))};
                                footer.items.forEach(m => {
                                    if (m.showWhen) {
                                    	m.show = m.showWhen[1].includes(n[m.showWhen[0]])
                                    } else {
        								m.show != undefined && (m.show = true);
        							}
                                })
                                footer.show = footer.items.some(m => m.show);
        						
        						newObj.__footer = footer;
        					}
        					if (mapper.iconConfig) {
        						if (mapper.iconConfig.type == 'file') {
        							newObj.__icon = vm.getFileIcon(n[mapper.iconConfig.targetProp]);
        						}
        					}
        					return newObj;
        				}));
						console.log(vm.list);
        			} else {
        				vm.list = vm.list.concat(listArray);
        			}
        			
        			if (vm.list.length == 0) {
        				vm.isEmpty = true;
        			}
        		});
        	},
			onSearchBarSearch: function () {
				if (this.toolBar.searchBar.value)  {
					this.toolBar.searchBar.queryString = '&' + (this.toolBar.searchBar.key || 'keyword') + '=' + this.toolBar.searchBar.value;
				} else {
					this.toolBar.searchBar.queryString = '';
				}
				this.getList(1);
			},
        	getFmtStr (str, n, preventIfNull) {
 				var vm = this;
				let routes = getCurrentPages();
				let curParam = routes[routes.length - 1].options;
				return str.replace(/【([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*】/g, function (d) {
					var prop = d.slice(1, -1);
                    if (prop == 'openId') {
                        return vm.openId;
                    } else if (n[prop] || n[prop] == 0) {
                        return n[prop];
                    } else {
                        return preventIfNull ? d : '';
                    }
				}).replace(/《([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*》/g, function (d) {
					var prop = d.slice(1, -1);
					return (vm.filterObject && vm.filterObject.queryObj || {})[prop] || '';
				}).replace(/\{([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*\}/g, function (d) {
					var prop = d.slice(1, -1);
					return curParam[prop] || '';
				}).replace(/》([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*《/g, function (d) {
					var prop = d.slice(1, -1);
					return uni.getStorageSync(prop) || '';
				});
        	},
        	getFileIcon: function (filename = '') {
        		var fileType = filename.replace(/.+\./, "");
        		var iconPackagesPrefix = '/static/imgs/fileIcons/';
        		var iconMap = {
        			"aep":"aep.png","ai":"ai.png","avi":"avi.png","cdr":"cdr.png","css":"css.png",
        			"doc":"doc.png", "docx":"doc.png","ppt":"ppt.png","pptx":"ppt.png",
        			"xls":"xls.png", "xlsx":"xls.png",
        			"eps":"eps.png","gif":"gif.png","html":"html.png","jpeg":"jpeg.png",
        			"mov":"mov.png","mp3":"mp3.png","new":"new.png","pdf":"pdf.png","php":"php.png",
        			"png":"png.png","psd":"psd.png","rar":"rar.png",
        			"ttf":"ttf.png","txt":"txt.png","url":"url.png","zip":"zip.png"
        		};
        		if (iconMap[fileType]) {
        			return iconPackagesPrefix + iconMap[fileType];
        		} else {
        			return iconPackagesPrefix + 'new.png';
        		}
        
        	},
        	back: function () {
        		uni.navigateBack();
        	},
        	handleExtButtonClick: function (obj, item) {
        		var vm = this;
        		vm.throttle();
        		// debugger
        		if (obj.url) {
        			vm.gotopage(vm.getFmtStr(obj.url, item), obj.label, item);
        		} else if (obj.event) {
        			if (obj.event == 'scan') {
						global.scanItem = item;
        				vm.scanQrCode();
        			} else if (obj.event == 'phoneCall') {
        				uni.makePhoneCall({
        					phoneNumber: item[obj.prop]
        				})
        			}
        		} else if (obj.h5) {
        			vm.gotoH5Page(vm.getFmtStr(obj.h5, item, true));
        		} else if (obj.api) {
                    var apiUrl = vm.getFmtStr(obj.api, item);
        
        			uni.showModal({
        				title: '提示',
        				content: obj.apiBeforeTip || '是否确定操作',
        				showCancel: true,
        				success: function(res2) {
        					if(res2.confirm) { 
        						uni.showLoading();
        						vm.getAndLoad('请求接口', apiUrl, function (res) {
        							uni.hideLoading();
        							uni.showModal({
        								title: '提示',
        								content: res.msg || (res.code == 0 ? '操作成功' : '操作失败'),
        								showCancel: false,
        								success: function(res3) {
        									if (res.code == 0) {
        										vm.page = 1;
        										vm.getList();
        									}
        								}
        							});
        						});
        					}
        					
        				}
        			});
        
        
        
        
                } else {
        			vm.showDetailCommon(item);
        		}
        	},
        	gotopage(url,title,item){
        		if(!url){
        			return;
        		}
        		console.log(url+'?id=' + item.id+'&title='+title)
        		uni.navigateTo({
        			url: url
        		})
        	},
        }
    }
</script>


<style lang="scss" scoped>
.menuBar {
	/deep/ {
		.u-tabs__wrapper__nav__line {
			height: 8rpx !important;
			background: linear-gradient(90deg, #ffb13c, rgba(255,60,60,0.55)) !important;
			border-radius: 10rpx !important;
		}
	}
}
.toolBar {
	.searchTool {
		padding: 20rpx;
	}
}
.add image {
	width: 122rpx;
	height: 122rpx;
	position: fixed;
	right: 10rpx;
	bottom: 140rpx;
	bottom: calc(140rpx + constant(safe-area-inset-bottom));
	bottom: calc(140rpx + env(safe-area-inset-bottom));
}

.list-area {
	background: #fff;
	position: relative;
    &.card {
        background: unset;
        .listItem {
            border-radius: 20rpx;
            margin: 20rpx 30rpx 20rpx;
            padding: 20rpx 30rpx 15rpx 30rpx;
            border-bottom: unset;
			.item-right {
				width: 100%;
				.lenMain .mainTitle {
					font-size: 30rpx;
					font-weight: bold;
				}
			}
            .v {
                color: #676767;
            }
        }
    }
	.disableBlock {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: #000;
		opacity: 0.4;
		padding-bottom: 120px;
    	box-sizing: content-box;
	}
	.listItem {
		background: #fff;
		padding: 20rpx 10rpx 15rpx 10rpx;
		border-bottom: 1px solid #ECECEC;
		box-sizing: border-box;
		margin: 0 10rpx 5rpx;
		display: flex;

		.item-icon  {
			min-width: 100rpx;
			image {
				width: 80rpx;
				height: 80rpx;
			}
		}
		.item-right {
			display: flex;
			flex-direction: column;
			flex-grow: 1;
			.lenMain  {
				display: flex;
				line-height: 50rpx;
				/deep/ .u-tag-wrapper {
					margin-right: 10rpx;
					.u-tag--medium {
						height: 22px;
						line-height: 20px;
						padding: 0 4px;
					}
				}
				.mainTitle {
					font-size: 32rpx;
					color: #414141;
					@include overfloewEllipsis(1);
					flex-grow: 1;
				}
				.titleTag {
					background: #eef5fd;
					color: #5890dc;
					padding: 0 10rpx;
					font-size: 26rpx;
					height: 44rpx;
					line-height: 44rpx;
					white-space: nowrap;
					margin-left: auto;
				}
			}
			.lens {
				display: flex;
				flex-direction: column;
				.len {
					display: flex;
					.fieldItem {
						display: flex;
						align-items: center;
						color: #BEBEBE;
						line-height: 46rpx;
						font-size: 26rpx;
						flex: 1;
						white-space: nowrap;
						overflow: hidden;
						.k {
    						// margin-right: 10rpx;
						}
						.v {
							overflow: hidden;
							text-overflow: ellipsis;
						}
					}
				}
			}
		}
		.buttons {
			height: 70rpx;
			display: flex;
			align-items: center;
			margin: 0 0 0 auto;
			&.mul {
				// width: 100%;
				justify-content: space-evenly;
			}
			.button {
				margin: 0 30rpx 0 -10rpx;
			}
		}
	}
}
.filer-dropdown {
	padding: 0 20rpx;
    color: #737373;
	.dropdownItem {
		display: flex;
		aligin-items: center;
		.trangle {
			display: flex;
			margin-left: 5rpx;
		}
		&.active {
			.trangle {
				transform: rotate(180deg);
			}
		}
	}
	.dropDownBroad {
		.categories {
			display: flex;
			flex-wrap: wrap;
			max-height: 450rpx;
			overflow-y: auto;
			padding-bottom: 40rpx;
			.item {
				color: #868686;
				background: #F5F5F5;
				width: 30%;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 10rpx auto 10rpx 0;
    			text-align: center;
				padding: 0px 20rpx;
				box-sizing: border-box;
				&.active {
					color: #1A97EE;
					background: #D9EAFB;
				}
			}
		}
		.confrimbar {
			position: absolute;
			width: 100%;
			left: 0;
			height: 70rpx;
			background: #fff;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-top: 1px solid #DADBDC;
			.btn {
				text-align: center;
				flex: 1;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				&.confirm {
					background: #0096FF;
					color: #fff;
				}
			}
		}
	}
}
</style>

